import 'dart:core';
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shop/tools/dio/interpretors.dart';

//商品类要：
//1.使用product_id查整个商品的信息,查modified，删除这个商品
//2.发出请求直接返回所有没有卖出（sell_status==0）的商品
//3.上传单个商品的信息对原有的商品进行修改，或者只修改purchaserid（也可以不单独做）
//4.发送请求获得一个商品id

class ProductPref {
  int? id;
  //id从服务器获取后再一并提交

  double? price;

  int status = 0;
  //商品售出状态,0为未卖出,1为卖出,-1为商品处于非正常状态（被举报下架或者正在交易）
  int createdAt = 0;
  //时间戳
  String name = "";
  //商品的名称
  String intro = "卖家没有输入更多信息哦~";
  //商品的详细信息
  String category = "";
  //商品的类，备用
  List<String> imgUri = [];
  //商品的图片，后续独立传给服务器
  String createrID = "";

  List<String> connection = [];

  //商品在发布之后是否有被修改过，默认未被修改过为0，修改过为1

  ProductPref();
  //只接受map和json

  fromMap(Map<String, dynamic> input) {
    id = input['product_id'];
    name = input['product_name'];
    price = input["product_price"];
    status = input['sell_status'];
    createdAt = input['product_created_time'];
    intro = input["product_intro"];
    imgUri = input["product_coverimg"];
    category = input["product_zone"];
    createrID = input["seller_id"];
    connection = input["connection"];
  }

  fromJson(String jsonString) {
    Map<String, dynamic> jsonMap =
        json.decode(jsonString) as Map<String, dynamic>;
    fromMap(jsonMap);
  }

  Map toMap() => {
        //"product_id": id,
        'product_name': name,
        "product_price": price,
        'sell_status': status,
        "product_intro": intro,
        'product_created_time': createdAt,
        "seller_id": createrID,
        "product_zone": json.encode(category),
        'product_coverimg': json.encode(imgUri),
        "connection": json.encode(connection),
      };

  String toJson() => json.encode(toMap());
}

class Product {
  ProductPref info;

  final BaseOptions _options = BaseOptions(
    //服务器地址
    baseUrl: "http://192.168.0.100:9000",
    connectTimeout: 5000,
    sendTimeout: 3000,
  );

  static Product? _cache;

  static var dio = Dio(_cache?._options);

  factory Product() => _cache ?? Product.init();

  Product.init() : info = ProductPref() {
    _cache = this;
    dio.interceptors.add(LogInterceptor());
    dio.interceptors.add(AuthInterCeptor());
  }

  static Future<List<Map>> productInfoInit() async {
    var res = await dio.get("/init");
    SharedPreferences uPrefs = await SharedPreferences.getInstance();
    List<Map> productlistmap = jsonDecode(res.data);
    List<String> productliststring = [];
    for (int i = 0; i < productlistmap.length; i++) {
      productliststring.add(jsonEncode(productlistmap[i]));
    }
    uPrefs.setStringList("ListofAllProduct", productliststring);
    //实际上是List<Json>;
    return productlistmap;
  }

  static Future<Map> getproductThroughid(String id) async {
    var res = await dio.post("/product/search/1", data: id);
    //默认/search/1返回全部
    if (res.statusCode == 200) {
      ProductPref p = ProductPref().fromJson(res.data);
      return p.toMap();
    } else {
      return {};
    }
  }

  //Future<int> getModifiedStatusStatus(String id) async {
  //  var req = await dio.post("/product/search/2", data: id);
  //  //默认/search/2返回hasmodified
  // if (req.statusCode == 200) {
  //    return json.decode(req.data)["ModifiedStatus"];
  //  } else {
  //    return 0;
  //  }
  //}

  static Future<Map> updateProduct(Map<String, dynamic> productmap) async {
    var res = await dio.post("/product/update", data: json.encode(productmap));
    Map jMap = res.data as Map<String, dynamic>;
    return jMap["msg"];
  }

  static Future<String> productCoverImgUrlGet(String imagepath,String imagename) async{
    var formData = FormData.fromMap({
      'file': await MultipartFile.fromFile(imagepath,filename: 'upload.png')
    });
    var res = await dio.post('', data: formData);
    return res.data;
  }

  static reportillegalgoods(String id) async{
    var res = await dio.post("/product/report", data: id);
    Map jMap = res.data as Map<String, dynamic>;
    if(jMap['msg']==200){

    }
  }
}
